﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AspCategoriesEdit
{
    public class DataLayer
    {
        public static Category FindCategoryById(int id)
        {
            CategoriesDataContext contex = new CategoriesDataContext();
            var res =
                (from c in contex.Categories
                 where c.CategoryID == id
                 select c).FirstOrDefault();
            return res;
        }

        public static void Edit(int id, string name, string description)
        {
            CategoriesDataContext contex = new CategoriesDataContext();
            var res =
                (from c in contex.Categories
                 where c.CategoryID == id
                 select c).FirstOrDefault();
            if (res != null)
            {
                res.CategoryName = name;
                res.Description = description;
                contex.SubmitChanges();
            }
        }

        public static void Delete(int id)
        {
            CategoriesDataContext contex = new CategoriesDataContext();
            var res =
                (from c in contex.Categories
                 where c.CategoryID == id
                 select c).FirstOrDefault();
            if (res != null)
            {
                contex.Categories.DeleteOnSubmit(res);
                contex.SubmitChanges();
            }
        }

        public static void Add(string name, string description)
        {
            CategoriesDataContext contex = new CategoriesDataContext();
            Category newCat = new Category()
            {
                CategoryName = name,
                Description = description
            };

            contex.Categories.InsertOnSubmit(newCat);
            contex.SubmitChanges();
        }
    }
}